<template>
  <div class="ele-body">
    <!-- 数据表格 -->
    <el-card shadow="always" body-style="padding: 30px 40px">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="关键字：">
          <el-input
            style="width: 400px"
            v-model="formInline.title"
            placeholder="关键字"
          ></el-input>
        </el-form-item>

        <el-form-item label="状态：">
          <el-select v-model="formInline.status" placeholder="请选择状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            @click="handleOpen"
            style="margin-left: 30px"
            type="primary"
            >新增<i class="el-icon-plus el-icon--right"></i
          ></el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="100" label="序号">
        </el-table-column>
        <el-table-column prop="name" label="图片" width="120">
          <template slot-scope="scope">
            <el-image
              style="max-width: 100%; height: 100px"
              :src="scope.row.imgUrl"
              :preview-src-list="[scope.row.imgUrl]"
            >
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="产品编号" width="120">
        </el-table-column>
        <el-table-column prop="name" label="产品名称" width="250">
        </el-table-column>
         <el-table-column prop="categoryName" label="产品分类" width="100">
        </el-table-column>
        <el-table-column prop="unitName" label="单位" width="80">
        </el-table-column>
        <el-table-column prop="origin" label="产地" width="130">
        </el-table-column>
        <el-table-column prop="isBoutique" label="是否精品" width="80">
          <template slot-scope="scope">
            <p>{{ scope.row.isBoutique ? '是' : '否' }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="最低销售价" width="120">
        </el-table-column>
        <el-table-column prop="status" label="是否上架" width="80">
          <template slot-scope="scope">
            <p>{{
              scope.row.status == 0
                ? '待上架'
                : scope.row.status == 1
                ? '已上架'
                : '已下架'
            }}</p>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120">
          <template slot-scope="scope">
            <el-button type="text" @click="onEdit(scope.row.id)" size="small"
              >编辑</el-button
            >
            <el-popconfirm
              @confirm="onConfirm(scope.row.id)"
              title="确定删除吗？"
            >
              <el-button
                style="margin-left: 20px; color: red"
                slot="reference"
                type="text"
                size="small"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="display: flex; justify-content: flex-end"
        background
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        :current-page.sync="currentPage"
        :total="totalNum"
        :page-size="10"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      width="65%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="right"
        label-width="90px"
        :model="form"
        :inline="false"
      >
        <el-row :gutter="24" style="margin-bottom: 15px">
          <el-col :span="6">
            <el-form-item label="产品名称" prop="name">
              <el-input
                show-word-limit
                maxlength="30"
                style="width: 200px"
                v-model="form.name"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产品编号" prop="code">
              <el-input
                show-word-limit
                maxlength="30"
                style="width: 200px"
                v-model="form.code"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
            <el-col :span="6">
            <el-form-item label="产品分类" prop="categoryId">
              <el-select v-model="form.categoryId" placeholder="请选择产品分类">
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="6">
            <el-form-item label="是否上架" prop="code">
              <el-select v-model="form.status" placeholder="请选择是否上架">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" style="margin-bottom: 15px">
          <el-col :span="6">
            <el-form-item label="单位" prop="unitId">
              <el-select v-model="form.unitId" placeholder="请选择单位">
                <el-option
                  v-for="item in dictionaryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="产地" prop="origin">
              <el-input
                show-word-limit
                maxlength="30"
                style="width: 200px"
                v-model="form.origin"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="浓度" prop="density">
              <el-input
                show-word-limit
                maxlength="30"
                style="width: 200px"
                v-model="form.density"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成分" prop="component">
              <el-input
                show-word-limit
                maxlength="30"
                style="width: 200px"
                v-model="form.component"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="是否精品" prop="isBoutique">
              <el-select v-model="form.isBoutique" placeholder="请选择状态">
                <el-option
                  v-for="item in optionsList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="产品描述" prop="content">
              <el-input
                style="width: 800px"
                :rows="3"
                type="textarea"
                placeholder="请输入备注"
                v-model="form.content"
                maxlength="500"
                show-word-limit
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
         <el-form-item label="产品规格">
        <el-row :gutter="24">
          <el-col :span="24">

              <el-table style="width: 100%;margin-left: -68px;margin-top: 10px;" :data="form.productItemList" ref="productItemTable" border>
                 <el-table-column type="index" width="50" align="center" label="序号" />
                  <el-table-column label="规格名称">
                 <template slot-scope="{ row ,$index}">
                      <el-select v-if="row.isEdit" filterable allow-create v-model="row.productItemId" placeholder="请选择规格" class="ele-fluid" @change="(v)=>changeProductItem(v,$index)">
                        <el-option v-for="item in productItemDatas" :key="item.id" :label="item.itemName" :value="item.id" />
                      </el-select>
                      <span v-else>{{ row.itemName }}</span>
                  </template>
                </el-table-column>
   
                <el-table-column
                  prop="content"
                  label="线上售价"
                  min-width="220"
                >
                  <template slot-scope="scope">
                    <el-input-number
                      v-model="scope.row.salePrice"
                      :min="0.1"
                      :max="10000000"
                      label="请输入线上销价"
                    ></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="300">
                  <template slot-scope="scope">
                    <el-button
                      style="margin-left: 20px; color: red"
                      type="text"
                      size="small"
                      @click="deleteProductItem(scope.$index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
             <el-button icon="el-icon-plus" style="width: 100%; margin-top: 15px" v-if="!this.isDetail" @click="addAtt">新增规格 </el-button>
          </el-col>
        </el-row>
     </el-form-item>
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="title === '新增设备'" type="primary" @click="addBanner"
          >确 定</el-button
        >
        <el-button
          v-if="title === '编辑设备'"
          type="primary"
          @click="editBanner"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getProductList,
  GetGuid,
  AddProduct,
  UploadFile,
  QueryProductById,
  DeleteProduct,
  GetAllModels,
  QueryAllChildDictViewByCode,
  UpdateProduct
} from '@/api/invoicingmanager';
import { QueryProductSpecitemsByCondition} from '@/api/basicdatamanager';
export default {
  name: 'Banner',
  props: {
            //详情
            isSelect:Boolean,
            // 弹窗是否打开
            visible: Boolean,
            // 修改回显的数据
            data: Object,
            // 是否查看详情
            isDetail:Boolean,
        },
  data() {
    return {
      itemDeatail: {},
      title: '',
      limit: 1,
      guid: '',
      currentPage: 1,
      totalNum: 0,
      dictionaryList: [],
      categoryList:[],
      productItemDatas:[], 
      optionsList: [
        {
          value: 0,
          label: '否'
        },
        {
          value: 1,
          label: '是'
        }
      ],
      options: [
        {
          value: 0,
          label: '待上架'
        },
        {
          value: 1,
          label: '已上架'
        },
        {
          value: 5,
          label: '已下架'
        }
      ],
      formInline: {
        title: '',
        status: ''
      },

      tableData: [],
      dialogFormVisible: false,
      form: {
        name: '',
        code: '',
        unitId: '',
        categoryId:'',
        status: '',
        origin: '',
        density: '',
        component: '',
        isBoutique: '',
        content: '',
        fileList: [],
        productItemList: []
      },
      rules: {
        name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        categoryId: [{required: true,message: '请输入产品分类',trigger: 'blur'}]
      },
       // TSelectTable 可搜索表格配置
        configure: {
            columns: 
            [

              { prop: 'itemCode', title: '编号' ,width:'149px' },
              { prop: 'itemName', title: '名称',width:'149px'  }
            ],
            keywords: {
              label: 'itemName',
              value: 'itemCode',
            },
            tablePagination: {
                total: 0, // 总数
                currentPage: 1, // 当前页码
                pageSize: 10, // 当前页面大小
            }
        }
    };
  },
  created() {
    this.initData();
    this.getGuid();
   // this.getAll();
    this.getDictionary();
    this.getCategory();
  },
  methods: {
    //新增配件属性
          addAtt(){
   
            if(this.form.productItemList ==null || this.form.productItemList == undefined){
              this.form.productItemList = [];
            }
     console.log('ok', this.form.productItemList);
            this.form.productItemList.push({
              id:'',
              productItemId:'',
              isEdit:true,
              itemName:'',
              salePrice:0.1
            });
          },

    deleteProductItem(index) {
      this.form.productItemList.splice(index, 1);
    },
    
          // 获取字典值
    getDictionary() {
      QueryAllChildDictViewByCode({
        code: 'DW'
      }).then((res) => {
        console.log('res>>>>>>>>>>1', res);
        this.dictionaryList = res;
      });
    },
    // 获取字典值
    getCategory() {
      QueryAllChildDictViewByCode({
        code: 'SPFL'
      }).then((res) => {
        console.log('res>>>>>>>>>>1', res);
        this.categoryList = res;
      });
    },
     //选择规格
      changeBrand(val,index){
        let productItem = this.productItemDatas.find((p)=>p.id === val)
        if(productItem==null || productItem == undefined){
            this.$refs.productItemTable.data[index].itemName = val;
        }
      },
    // 获取所有规格
    getAll() {
      GetAllModels()
        .then((res) => {
          let arr = [];
          res.forEach((item) => {
            arr.push({
              productItemId: item.id,
              salePrice: 0.1,
              itemName: item.itemName
            });
          });
          this.$set(this.form, 'productItemDatas', arr);
          console.log(this.form.productItemDatas);
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initData();
    },
    // 文件上传
    handleChange(file, fileList) {
      this.$set(this.form, 'fileList', fileList);
      this.uploadImg();
    },
    // 上传图片
    uploadImg() {
      let fdata = new FormData();
      fdata.set('file', this.form.fileList[0].raw);
      fdata.set('imgType', 4); //图片类型
      fdata.set('attType', 1); //文件类型
      fdata.set('businessId', this.guid); // 业务ID
      //上传文件
      UploadFile(fdata)
        .then((res) => {
          console.log(this.form);
          this.$refs.ruleForm.validateField('fileList');
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    initData() {
        /* 初始配件数据 */
    
      getProductList({
        pageIndex: this.currentPage,
        pageSize: 10,
        conditions: {
          keyword: this.formInline.title,
          status: this.formInline.status
        },
        orderBys: [
          {
            sort: 'createDate',
            order: 0
          }
        ]
      })
        .then((res) => {
          console.log(res);
          this.tableData = res.items;
          this.totalNum = res.totalrecords;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    onEdit(id) {
      this.title = '编辑设备';
      this.guid = id;
      this.getDetail(id);
      this.dialogFormVisible = true;
    },
    getDetail(id) {
      QueryProductById({
        id: id
      })
        .then((res) => {
          this.form = {
            name: res.name,
            code: res.code,
            unitId: res.unitId,
            status: res.status,
            origin: res.origin,
            density: res.density,
            component: res.component,
            isBoutique: res.isBoutique,
            categoryId:res.categoryId,
            content: res.content,
            productItemList: res.productItems
          };
          this.itemDeatail = res;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    editBanner() {
      for (let i = 0; i < this.form.productItemList.length; i++) {
        if (!this.form.productItemList[i].salePrice) {
          this.$message.error('请输入正确的价格');
          return;
        }
      }
      UpdateProduct({
        ...this.form,
        createDate: this.itemDeatail.createDate,
        id: this.guid
      })
        .then((res) => {
          this.$message.success('修改成功');
          this.dialogFormVisible = false;
          this.initData();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    addBanner() {
      for (let i = 0; i < this.form.productItemList.length; i++) {
        if (!this.form.productItemList[i].salePrice) {
          this.$message.error('请输入正确的价格');
          return;
        }
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          AddProduct({ ...this.form })
            .then((res) => {
              this.$message.success('新增成功');
              this.dialogFormVisible = false;
              this.initData();
            })
            .catch((e) => {
              this.$message.error(e.message);
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    delItem(id) {
      DeleteProduct({ id: id })
        .then((res) => {
          this.$message.success('删除成功');
          this.initData();
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    onConfirm(id) {
      this.delItem(id);
    },
    handleSearch() {
      this.currentPage = 1;
      this.initData();
    },
    handleReset() {
      this.formInline = {};
      this.currentPage = 1;
    },
    getGuid() {
      GetGuid()
        .then((res) => {
          this.guid = res;
        })
        .catch((e) => {
          this.$message.error(e.message);
        });
    },
    handleOpen() {
      this.title = '新增设备';
      this.form = {};
      this.getGuid();
     // this.getAll();
      this.dialogFormVisible = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>